#!/usr/bin/perl -w
use strict;
my $evalue_cutoff = 1e-5;
# this is hardcoded for now
my @names = qw(tmes B3501 CNAG R265);

my $dir = shift @ARGV;
opendir(DIR, $dir) || die "$dir: $!";
foreach my $fastafile ( readdir(DIR) ) {
    if( $fastafile =~ /(\S+)\.fa$/ ) {
        my $stem = $1;
        open(IN, $fastafile) || die $!;
        my %species_count;
        while(<IN>) {
            if( />(\S+)/ ) {
                my ($species) = split(/_/,$1);
                $species_count{$species}++;
            }
        }
	# let's store the domains we see in this hash
	my %domains;
        # get the domains from the Pfam outputfile here
        open(PFAM, "$fastafile.tab") || die $!;
        while(<PFAM>){
	    # skip lines that start with '#'
	    if( /^\#/ ) { 
		next;
	    }
            # get the domains
	    
            my ($domain,$domain_acc,$target, $target_acc, $evalue) =split(/\s+/,$_);
	    if( $evalue > $evalue_cutoff) {
		# skip domains that have Evalue > 1e-5;
		next;
	    }
	    # $domains{$domain}++;
	    push @{$domains{$domain}}, $evalue;
	}
	#print join("\t", $stem, $species_count{$names[0]} || 0,
	#	   $species_count{$names[1]} || 0,
	#	   $species_count{$names[2]} || 0,
	#	   $species_count{$names[3]} || 0,
	#	   join(',',@domains)), "\n";
	# OR a very perl way
	
	my @counts;
	foreach my $species ( @names ){
	    push @counts, $species_count{$species};
	}
	my @domains_seen = sort keys %domains;
	print join("\t", $stem, @counts,
		   join(",", @domains_seen),
		   ),"\n";
	# (map { $species_count{$_} } @names)
    }
}
